import java.util.Arrays;

public class TestHeap {
    private int[] elem;

    private int usedSize;
    public TestHeap() {
        this.elem = new int[10];
    }

    public void init(int[] arr) {
        if(arr.length > elem.length) {
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            elem[i] = arr[i];
        }
        usedSize = arr.length;
    }

    public void createHeap() {
        for (int i = (usedSize - 1) / 2; i >= 0; i--) {
            siftDown(i, usedSize);
        }
    }

    private void siftDown(int parent, int len) {
        int child = parent * 2 + 1;
        while(child < len) {
            if(child + 1 < len && elem[child] < elem[child + 1]) {
                child++;
            }
            // 此时 elem[child] 是子树的较大者
            if(elem[child] > elem[parent]) {
                swap(parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        siftUp(usedSize);
        usedSize++;
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    private void swap(int i, int j) {
        int tmp = elem[i];
        elem[i] = elem[j];
        elem[j] = tmp;
    }

    private void siftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0) {
            if(elem[parent] < elem[child]) {
                swap(parent, child);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public int pop() {
        if(isEmpty()) {
            return -1;
        }
        int ret = elem[0];
        swap(0, --usedSize);
        siftDown(0, usedSize);
        return ret;
    }

    private boolean isEmpty() {
        return usedSize == 0;
    }

    public void sortHeap() {
        int end = usedSize - 1;// 表示此时大根堆的范围
        while(end > 0) {
            swap(0, end);// 将最大的放到最后面
            siftDown(0, end);
            end--;
        }
    }
}
